package com.changer.common.component;

import com.changer.common.vo.ChangerToken;
import com.changer.common.vo.Constants;
import com.changer.framework.util.MD5Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

/**
 * Created by pangk on 2016/5/9.
 */
public class TokenManager {
    public static final String SPLIT_CHAR = "-";

    public static ChangerToken generateToken(HttpServletRequest request,String userId) throws Exception {
        UUID uuid = UUID.randomUUID();
        String randmonUID = uuid.toString();
        String tokenString = token(request,userId,randmonUID);
        ChangerToken changerToken = new ChangerToken();
        changerToken.setId(tokenString);
        changerToken.setLastUsingTime(System.currentTimeMillis());
        changerToken.setRandomStr(randmonUID);
        return changerToken;
    }

    public static boolean validateToken(HttpServletRequest request,String userId,ChangerToken cacheToken) throws Exception {
        String tokenString = token(request,userId,cacheToken.getRandomStr());
        if (tokenString.equals(cacheToken.getId())){
            return true;
        }
        return false;
    }

    private static String token(HttpServletRequest request,String userId,String random) throws Exception {
        String appKey = request.getHeader(Constants.TOKEN_KEY_APP_KEY);
        String udid = request.getHeader(Constants.TOKEN_KEY_UDID);
        String tokenString = MD5Utils.encode(udid+SPLIT_CHAR+appKey+SPLIT_CHAR+userId+SPLIT_CHAR+random);
        return tokenString;
    }
}
